package cs271.hw.liststackqueue;

import cs271.hw.liststackqueue.interfaces.SimpleList;

public class SinglyLinkedList<T> implements SimpleList<T> {

	private ElementHolder head, tail;
	
	public SinglyLinkedList(){
		
	}
	

	public void add(T item) {
		ElementHolder temp = new ElementHolder();
		temp.item = item;
		if (head == null){
			head = temp;
			tail = temp;
		}
		tail.next = temp;
		tail = temp;	
	}
	
	
	public T get(int index) {
		//return null when called on invalid index (i.e. out of bounds, negative, empty list, etc) 
		ElementHolder temp = head;
		int counter = 0;
		if (index < size() && index > -1)
			while (temp != null){
				if (counter == index)
					return temp.item;
				counter ++;
				temp = temp.next;
			}		
		return null;
	}
	
	public T remove(int index)
	{
		try {
		ElementHolder front = head;
		ElementHolder temp = head.next;
		ElementHolder var;
		
		
			if (index == 0){
				var = head;
				head = head.next;	
				return var.item;
			}
			else {
				int count = 1;
				while (temp != null){
					if (count == index){
						var = temp;
						front.next = temp.next;	
						temp = null;
						return var.item;
					}					
					count ++;
					front = front.next;
					temp = temp.next;
				}
				
			}
		} catch (NullPointerException e){
			System.out.println("Exception Handling : " + e);
		}
		return null;
	}	
	

	public boolean isEmpty() {
		return head == null;
	}
	
	
	public int size() {
		int count = 0;
		if (head == null){
			return 0;
		}
		else {
			
			for (ElementHolder current = head; current != null; current = current.next)
				count++;
			return count;
		}
		
	} 
	
	private class ElementHolder {
		public T item;
		public String data;
		public ElementHolder next;
	}
}


